import { _decorator, Component, Node, UIOpacity, Sprite, Label } from 'cc';
import { Global } from '../../Global';
import { Conversation } from './def/Conversation';
const { ccclass, property } = _decorator;

@ccclass('ConversationManage')
export class ConversationManage extends Component {

    @property(UIOpacity)
    private op: UIOpacity = null

    @property(Sprite)
    private avator: Sprite = null

    @property(Label)
    private role: Label = null

    @property(Label)
    private conv: Label = null

    @property(Label)
    private next: Label = null

    private _currentConv: Conversation[] = null

    private _currentConvStep: number = 0

    private _call: Function = null

    start() {
        Global.convManage = this
        this.node.active = false
    }

    update(deltaTime: number) {

    }

    startConversation(convs: Conversation[], call?: Function) {
        Global.key.globalMoveKey = true
        this.node.active = true
        this._currentConv = convs
        this._call = call
        // 初始化首个对话
        this.initConv()
        // 展示
        this.show()
    }

    private initConv() {
        this.playConversation()
    }

    private show() {
        const inter = setInterval(() => {
            let op = this.op.opacity + 10
            if (op >= 255) {
                this.op.opacity = 255
                clearInterval(inter)
            } else {
                this.op.opacity = op
            }
        }, 10)
    }

    private playConversation() {
        this.next.string = this._currentConvStep >= this._currentConv.length - 1 ? '结束对话' : '点击继续'
        const conv = this._currentConv[this._currentConvStep]
        this.avator.spriteFrame = conv.avator
        this.role.string = this.getName(conv.role)
        this.conv.string = conv.caption
    }

    private hidden() {
        Global.key.globalMoveKey = false
        this.op.opacity = 0
        this.node.active = false
        this._call()
    }

    public nextConv() {
        // 结束
        if (this._currentConvStep >= this._currentConv.length - 1) {
            this.hidden()
            return
        }
        this._currentConvStep += 1
        this.playConversation()
    }

    private getName(role: string) {
        switch (role) {
            case 'hero': {
                return '勇士'
            }
            case 'angel': {
                return '天使'
            }
        }
    }
}

